package br.uvv.Dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.primefaces.model.SortOrder;

import br.uvv.Model.CenarioBase;
import br.uvv.Util.DAOException;

@SuppressWarnings("unchecked")
public class CenarioBaseDAO extends DAO {

	private static final long serialVersionUID = 1644593689725160930L;

	public CenarioBase selecionar(Long id) throws DAOException {
		return (CenarioBase) get(CenarioBase.class, id);
	}
	
	public List<CenarioBase> listar() throws DAOException {
		return (List<CenarioBase>) list(CenarioBase.class, null);
	}
	
	public void salvar(CenarioBase cenarioBaseInstance) throws DAOException {
		save(cenarioBaseInstance, cenarioBaseInstance.getId());
	}
	
	public void remover(CenarioBase cenarioBaseInstance) throws DAOException {
		delete(CenarioBase.class, cenarioBaseInstance.getId());
	}
	
	public List<CenarioBase> listar(int first, int pageSize, String sortField, 
			SortOrder sortOrder, String nome) throws DAOException{
		Criterion[] filtros = { Restrictions.ilike("nome", "%" + nome + "%") };
		return (List<CenarioBase>) listPaginator(first, pageSize, sortField, sortOrder, CenarioBase.class, null, filtros);
	}
	
	public Integer count(String nome) throws DAOException {
		Criterion[] filtros = { Restrictions.ilike("nome", "%" + nome + "%") };
		return rowCount(CenarioBase.class, filtros);
	}

	public List<CenarioBase> listar(int first, int pageSize, String sortField,
			SortOrder sortOrder, String varNome, String varFluxo) throws DAOException {
		List<CenarioBase> cenarioBaseList = new ArrayList<CenarioBase>();
		try {
			begin();
			Criteria criteria = this.sessao.createCriteria(CenarioBase.class)
					.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
					.add(Restrictions.eq("nome", "%" + varNome + "%"))
					.createCriteria("fluxosBase")
					.add(Restrictions.eq("acao", "%" + varFluxo + "%"));
			criteria = montaPaginacao(criteria, first, pageSize, sortField, sortOrder);
			cenarioBaseList = criteria.list();
			commit();
		} catch (Exception e) {
			throw new DAOException(e);
		}
		return cenarioBaseList;
	}

	public int count(String varNome, String varFluxo) throws DAOException {
		Integer count = 0;
		try {
			begin();
			Criteria criteria = this.sessao.createCriteria(CenarioBase.class)
					.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
					.setProjection(Projections.rowCount())
					.add(Restrictions.eq("nome", "%" + varNome + "%"))
					.createCriteria("fluxosBase")
					.add(Restrictions.eq("acao", "%" + varFluxo + "%"));
			count = Integer.parseInt(criteria.uniqueResult().toString());
			commit();
		} catch (Exception e) {
			throw new DAOException(e);
		}
		return count;
	}
}
